package com.yneusoft.manage.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.dao.entity.Staff;
import com.yneusoft.dao.mapper.StaffManageMapper;
import com.yneusoft.manage.model.param.DeleteFileParam;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class MongodbOperationService {

    private final GridFsOperations gridFsOperations;
    public MongodbOperationService(GridFsOperations gridFsOperations) {
        this.gridFsOperations = gridFsOperations;
    }

    @Resource
    StaffManageMapper staffManageMapper;

    /**
     * 文件上传
     *
     * @param file 文件
     * @return map
     */
    public ResponseWrapper uploadFile(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        try (InputStream inputStream = file.getInputStream()) {
            //上传文件返回文件ID
            ObjectId objectId = gridFsOperations.store(inputStream, file.getOriginalFilename(), file.getContentType());
            System.out.println("文件ID == " + objectId);
            map.put("data", objectId.toString());
            map.put("code", 10000);
            map.put("message", "上传成功");
            //此处可以编写自己的业务逻辑,比如将ObjectID存入MySQL和用户一一对应
        } catch (IOException ioException) {
            ioException.printStackTrace();
            map.put("data", "");
            map.put("code", 99999);
            map.put("message", "上传失败");
        }
        return ResponseWrapper.markSuccess(map);
    }



    /**
     * 下载文件
     *
     * @param objectId 文件ID
     */
    public Map<String, Object> downloadFile(String objectId,HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>(2);
        //根据文件ID查询出文件
        GridFSFile gridFsFile = gridFsOperations.findOne(Query.query(Criteria.where("_id").is(objectId)));
        if (gridFsFile != null) {
            GridFsResource gridFsResource = gridFsOperations.getResource(gridFsFile);
        //设置响应对象的响应内容的类型
            response.setCharacterEncoding("UTF-8");
            response.setContentType(gridFsResource.getContentType());
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String(gridFsFile.getFilename().getBytes(), StandardCharsets.ISO_8859_1));
            try (OutputStream outputStream = response.getOutputStream();
                 InputStream inputStream = gridFsResource.getInputStream()) {
            //读取inputStream中的所有字节并写入输出流中
                outputStream.write(inputStream.readAllBytes());
                map.put("code", 10000);
                map.put("message", "下载成功");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } else {
            map.put("code", 99999);
            map.put("message", "文件不存在");
        }
        return map;
    }


    /**
     * 删除文件
     *
     * @param param 文件ID
     */
    public ResponseWrapper deleteFile(DeleteFileParam param) {
        gridFsOperations.delete(Query.query(Criteria.where("_id").is(param.getEnclosureId())));
        LambdaUpdateWrapper<Staff> wrapper=new LambdaUpdateWrapper<>();
        wrapper.eq(Staff::getEnclosureId,param.getEnclosureId()).set(Staff::getEnclosureId,null);
        int i = staffManageMapper.update(null, wrapper);
        if(i>0){
            return ResponseWrapper.markSuccess();
        }else
            return ResponseWrapper.markError();

    }



}
